package com.mlink.ai.chat.utils

import android.app.Activity
import android.content.Context
import android.view.LayoutInflater
import android.widget.TextView
import androidx.appcompat.widget.AppCompatButton
import com.mlink.ai.chat.assistant.robot.R
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.icekrvams.air.mmkv
import com.icekrvams.air.versionchecker.LocalVersionChecker
import com.icekrvams.air.versionchecker.LocalVersionChecker.PREF_SHOULD_SHOW_UPDATE_DIALOG
import com.icekrvams.air.versionchecker.LocalVersionChecker.PREF_SHOULD_SHOW_WHATS_NEW_DIALOG
import com.icekrvams.air.versionchecker.RemoteVersionChecker
import com.icekrvams.air.versionchecker.VersionInfo

object UpgradeUtils {

    private const val PREF_REMOTE_VERSION_CODE = "remote_version_code"

    fun checkVersion(context: Context) {
        checkLocalVersion(context)
        checkRemoteVersion(context)
    }

    private fun checkLocalVersion(context: Context) {
        if (LocalVersionChecker.isFirstStartAfterUpgrade() &&
            mmkv.decodeBool(PREF_SHOULD_SHOW_WHATS_NEW_DIALOG)
        ) {
            LocalVersionChecker.getCurrentVersionName(context)
                ?.let { showWhatsNewDialog(context, it) }
        }
    }

    fun checkRemoteVersion(context: Context) {
        RemoteVersionChecker.checkNewVersion(context) { hasNewVersion, versionInfo ->
            if (!hasNewVersion || versionInfo == null) return@checkNewVersion
            showUpgradeDialog(context, versionInfo)
        }
    }

    /**
     * 升级提醒弹框，升级上来的用户，第一次打开应用时会弹该弹框
     * 弹框 UI 样式根据自己项目而定
     */
    private fun showWhatsNewDialog(context: Context, version: String) {
        mmkv.encode(PREF_SHOULD_SHOW_WHATS_NEW_DIALOG, false)
        val view = LayoutInflater.from(context).inflate(R.layout.dialog_whats_new, null)
        val builder = MaterialAlertDialogBuilder(context).setView(view)
        val dialog = builder.create().apply {
            window?.setBackgroundDrawableResource(R.color.transparent)
            window?.attributes?.width = 309.dp2px()
        }
        val titleTv = view.findViewById<TextView>(R.id.tv_title)
        val okBtn = view.findViewById<TextView>(R.id.btn_ok)
        titleTv.text = context.getString(R.string.whats_new_title, version)
        okBtn.setOnClickListener { dialog.dismiss() }
        dialog.show()
    }

    /**
     * 强制/非强制升级弹框
     * 弹框 UI 样式根据自己项目而定
     */
    private fun showUpgradeDialog(context: Context, versionInfo: VersionInfo) {
        if (!versionInfo.isCompulsoryUpgrading) {
            val preRemoteVersionCode = mmkv.decodeInt(PREF_REMOTE_VERSION_CODE, 0)
            val currentRemoteVersionCode = versionInfo.intVersioncode
            if (currentRemoteVersionCode > preRemoteVersionCode) {
                mmkv.encode(PREF_SHOULD_SHOW_UPDATE_DIALOG, true)
            }
            if (!mmkv.decodeBool(PREF_SHOULD_SHOW_UPDATE_DIALOG, true)) return
            mmkv.encode(PREF_SHOULD_SHOW_UPDATE_DIALOG, false)
        }
        mmkv.encode(PREF_REMOTE_VERSION_CODE, versionInfo.intVersioncode)
        val view = LayoutInflater.from(context).inflate(R.layout.dialog_upgrade, null)
        val builder = MaterialAlertDialogBuilder(context, R.style.CustomMaterialAlertDialog).setView(view)
        val dialog = builder.create().apply {
            setCancelable(false)
            setCanceledOnTouchOutside(false)
        }
        val versionTv = view.findViewById<TextView>(R.id.tv_version)
        versionTv.text = "V" + versionInfo.strVersionName
        val contentTv = view.findViewById<TextView>(R.id.tv_content)
        val cancelTv = view.findViewById<TextView>(R.id.tv_cancel)
        val upgradeTv = view.findViewById<AppCompatButton>(R.id.btn_upgrade)
        contentTv.text = versionInfo.strWhatsNew
        cancelTv.setOnClickListener {
            dialog.dismiss()
            if (versionInfo.isCompulsoryUpgrading) (context as Activity).finish()
        }
        upgradeTv.setOnClickListener {
            context.searchMyselfOnPlayStore()
            if (!versionInfo.isCompulsoryUpgrading) dialog.dismiss()
        }
        dialog.show()
    }
}